package com.fw.ui.view.settings.usercontrol.parentmerchant.event;

import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.fw.ui.view.common.PagedTable;
import com.fw.ui.view.common.TablePanel;
import com.fw.ui.view.event.AbstractPageTableButtonClickListener;
import com.fw.ui.view.settings.usercontrol.parentmerchant.EditParentMerchantView;
import com.vaadin.data.util.BeanItem;
import com.vaadin.ui.Button.ClickEvent;

@Component
@Scope(SCOPE_PROTOTYPE)
public class EditParentMerchantSelectedMerchantProfileTablePageButtonClickListener extends AbstractPageTableButtonClickListener {

    private static final long serialVersionUID = 1L;

    @SuppressWarnings("rawtypes")
    @Override
    public void click(ClickEvent event, int page, int size) throws Exception {
	EditParentMerchantView editParentMerchantView = (EditParentMerchantView) this.getBasedComponent();
	TablePanel tableMerchantSelectedPanel = editParentMerchantView.getTableMerchantSelectedPanel();
	PagedTable pagedSelectedTable = tableMerchantSelectedPanel.getTable();
	Map<Long, BeanItem> selectedBeanItemMap = editParentMerchantView.getSelectedBeanItemMap();
	List<BeanItem> selectedBeanItems = new ArrayList<BeanItem>(selectedBeanItemMap.values());
	int totalElements = selectedBeanItems.size();
	Integer itemPerPage = Integer.parseInt((String) pagedSelectedTable.getManualItemsPerPageSelect().getValue());
	int totalPage = Double.valueOf(Math.ceil(Double.valueOf(totalElements) / Double.valueOf(itemPerPage))).intValue();
	List<BeanItem> subItems = new ArrayList<BeanItem>();
	if (totalElements > 1) {
	    subItems = selectedBeanItems.subList((page - 1) * itemPerPage, totalElements);
	} else {
	    subItems = selectedBeanItems;
	}
	tableMerchantSelectedPanel.clearTableData();
	tableMerchantSelectedPanel.setTableBeanContainerDataTotalPage(subItems, totalPage, Long.valueOf(totalElements));
    }

    @Override
    public boolean validate(ClickEvent event, int page, int size) {
	return true;
    }
}